package fu.k4c.vTeam.ViewDetails;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import java.lang.reflect.Type;
import fu.k4c.vTeam.R;
import fu.k4c.vTeam.Main.BaseActivity;
import fu.k4c.vTeam.Main.MapBaseActivity;
import fu.k4c.vTeam.Object.Favorite;
import fu.k4c.vTeam.Object.ItemImage;
import fu.k4c.vTeam.Object.ItemViewPlace;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class InfoActivity extends MapBaseActivity {
	TextView tv_place_like_number;
	TextView tv_place_visit_number;
	Boolean visted;
	Boolean liked;
	String email;
	String PlaceID;
	Bundle data;
	List<ItemImage> ListImage;
	int likenumber;
	int visitnumber;
	private DisplayImageOptions options;
	int CURRENT_TAG = 0;
	static final int TAG_GUEST = 0;
	static final int TAG_USER = 1;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tab_view_place_details);
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.stub_image)
				.showImageForEmptyUri(R.drawable.image_for_empty_url)
				.cacheInMemory().cacheOnDisc()
				.displayer(new RoundedBitmapDisplayer(20)).build();
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
				.permitAll().build();
		StrictMode.setThreadPolicy(policy);
		final Button btn_like = (Button) findViewById(R.id.btn_view_tab_place_details_like);
		final Button btn_visit = (Button) findViewById(R.id.btn_view_tab_place_details_visit);
		btn_visit.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (CURRENT_TAG == TAG_GUEST) {
					Toast.makeText(
							getApplicationContext(),
							"Bạn phải đăng nhập để có thể sử dụng chức năng này",
							Toast.LENGTH_LONG).show();
				} else {
					if (visted) {
						Toast.makeText(getApplicationContext(),
								"Bạn đã đánh dấu đến địa điểm này",
								Toast.LENGTH_LONG).show();
					} else {
						try {
							SchemeRegistry registry = new SchemeRegistry();
							registry.register(new Scheme("http",
									PlainSocketFactory.getSocketFactory(), 80));
							HttpParams httpParams = new BasicHttpParams();
							ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(
									httpParams, registry);
							HttpClient client = new DefaultHttpClient(connMgr,
									httpParams);
							HttpPost post = new HttpPost(
									getString(R.string.connectionString)
											+ "vLocationService/checkin");
							post.setHeader("Accept", "application/json");
							post.setHeader("Content-type", "application/json");
							HashMap<String, Object> postParameters = new HashMap<String, Object>();
							postParameters.put("UserName", email);
							postParameters.put("PlaceId", PlaceID);
							Gson gson = new Gson();
							String jsonParameters = gson.toJson(postParameters);
							post.setEntity(new StringEntity(jsonParameters));
							HttpResponse response = client.execute(post);
							HttpEntity entity = response.getEntity();
							String jsonresult = EntityUtils.toString(entity);
							Favorite fvr = gson.fromJson(jsonresult,
									Favorite.class);
							if (fvr.getStatus().equals("true")) {
								btn_visit.setText("Bạn đã đến");
								visted = true;
								visitnumber += 1;
								tv_place_visit_number.setText("Đã có "
										+ visitnumber
										+ " người đến địa điểm này");
								btn_visit
										.setBackgroundResource(R.drawable.btn_checkin);
							} else {
								Toast.makeText(getApplicationContext(),
										"" + jsonresult, Toast.LENGTH_LONG)
										.show();
							}
						} catch (Exception e) {
							// TODO: handle exception
							Toast.makeText(getApplicationContext(),
									"loi 1 " + e.toString(), Toast.LENGTH_LONG)
									.show();

						}
					}
				}
			}
		});
		btn_like.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (CURRENT_TAG == 0) {
					Toast.makeText(
							getApplicationContext(),
							"Bạn phải đăng nhập để có thể sử dụng chức năng này",
							Toast.LENGTH_LONG).show();
				} else {
					if (liked) {
						try {
							SchemeRegistry registry = new SchemeRegistry();
							registry.register(new Scheme("http",
									PlainSocketFactory.getSocketFactory(), 80));
							HttpParams httpParams = new BasicHttpParams();
							ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(
									httpParams, registry);
							HttpClient client = new DefaultHttpClient(connMgr,
									httpParams);
							HttpPost post = new HttpPost(
									getString(R.string.connectionString)
											+ "vLocationService/addtofavoritelist");
							post.setHeader("Accept", "application/json");
							post.setHeader("Content-type", "application/json");
							HashMap<String, Object> postParameters = new HashMap<String, Object>();
							postParameters.put("UserName", email);
							postParameters.put("PlaceId", PlaceID);
							postParameters.put("Like", "Unlike");
							Gson gson = new Gson();
							String jsonParameters = gson.toJson(postParameters);
							post.setEntity(new StringEntity(jsonParameters));
							HttpResponse response = client.execute(post);
							HttpEntity entity = response.getEntity();
							String jsonresult = EntityUtils.toString(entity);
							Favorite fvr = gson.fromJson(jsonresult,
									Favorite.class);
							if (fvr.getStatus().equals("true")) {
								btn_like.setText("Thích");
								liked = false;
								likenumber -= 1;
								btn_like.setBackgroundResource(R.drawable.btn_unlike);
								tv_place_like_number.setText("Đã có "
										+ likenumber
										+ " người thích địa điểm này");
							} else {
								Toast.makeText(getApplicationContext(),
										"" + jsonresult, Toast.LENGTH_LONG)
										.show();
							}
						} catch (Exception e) {
							// TODO: handle exception
							Toast.makeText(getApplicationContext(),
									"loi 2" + e.toString(), Toast.LENGTH_LONG)
									.show();

						}
					} else {
						try {
							SchemeRegistry registry = new SchemeRegistry();
							registry.register(new Scheme("http",
									PlainSocketFactory.getSocketFactory(), 80));
							HttpParams httpParams = new BasicHttpParams();
							ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(
									httpParams, registry);
							HttpClient client = new DefaultHttpClient(connMgr,
									httpParams);
							HttpPost post = new HttpPost(
									getString(R.string.connectionString)
											+ "vLocationService/addtofavoritelist");
							post.setHeader("Accept", "application/json");
							post.setHeader("Content-type", "application/json");
							HashMap<String, Object> postParameters = new HashMap<String, Object>();
							postParameters.put("Like", "like");
							postParameters.put("PlaceId", PlaceID);
							postParameters.put("UserName", email);
							Gson gson = new Gson();
							String jsonParameters = gson.toJson(postParameters);
							post.setEntity(new StringEntity(jsonParameters));
							HttpResponse response = client.execute(post);
							HttpEntity entity = response.getEntity();
							String jsonresult = EntityUtils.toString(entity);
							Favorite fvr = gson.fromJson(jsonresult,
									Favorite.class);
							if (fvr.getStatus().equals("true")) {
								btn_like.setText("Bỏ thích");
								liked = true;
								likenumber += 1;
								btn_like.setBackgroundResource(R.drawable.btn_like);
								tv_place_like_number.setText("Đã có "
										+ likenumber
										+ " người thích địa điểm này");
							}
						} catch (Exception e) {
							// TODO: handle exception
							Toast.makeText(getApplicationContext(),
									"loi 3 " + e.toString(), Toast.LENGTH_LONG)
									.show();
						}
					}
				}
			}
		});
		TextView tv_place_name = (TextView) findViewById(R.id.tv_view_tab_place_details_placename);
		TextView tv_place_address = (TextView) findViewById(R.id.tv_view_tab_place_details_address);
		TextView tv_place_tel = (TextView) findViewById(R.id.tv_view_tab_place_details_tel_number);
		tv_place_like_number = (TextView) findViewById(R.id.tv_view_tab_place_details_person_like);
		tv_place_visit_number = (TextView) findViewById(R.id.tv_view_tab_place_details_person_visit);
		TextView tv_place_create_by = (TextView) findViewById(R.id.tv_view_tab_place_details_create_by);
		TextView tv_place_description = (TextView) findViewById(R.id.tv_view_tab_place_details_description);
		TextView tv_place_view = (TextView) findViewById(R.id.tv_view_tab_place_details_view);
		ImageView img_place_view = (ImageView) findViewById(R.id.img_view_tab_place_details_avatar);
		try {
			data = getIntent().getExtras();
			likenumber = data.getInt("likenumber");
			visitnumber = data.getInt("visitnumber");
			if (data != null) {
				email = data.getString("email");
				if (email.equals("Guest")) {
					CURRENT_TAG = TAG_GUEST;
				} else {
					CURRENT_TAG = TAG_USER;
				}
				tv_place_name.setText(data.getString("placename"));
				tv_place_address.setText(data.getString("address"));
				if (data.getString("placetel") == null) {
					tv_place_tel.setText("Số điện thoại: N\\A");
				} else
					tv_place_tel.setText("Số điện thoại:"
							+ data.getString("placetel"));
				tv_place_like_number.setText("Đã có "
						+ data.getInt("likenumber")
						+ " người thích địa điểm này");
				tv_place_visit_number.setText("Đã có "
						+ data.getInt("visitnumber")
						+ " người đến địa điểm này");
				tv_place_description.setText(data.getString("des"));
				tv_place_create_by.setText(data.getString("createby"));
				tv_place_view.setText("Đã có " + data.getString("views")
						+ " lượt xem");
				PlaceID = data.getString("IDofItemRevision");
				visted = data.getBoolean("visited");
				liked = data.getBoolean("liked");
				getImage();
				if (ListImage.size() != 0) {
					String[] imageUrls = new String[ListImage.size()];
					for (int i = 0; i < ListImage.size(); i++) {
						if (ListImage.get(i).getImage().toLowerCase()
								.indexOf("http://") >= 0) {
							imageUrls[i] = ListImage.get(i).getImage();

						} else {
							imageUrls[i] = getString(R.string.connectionString)
									+ ListImage.get(i).getImage();
						}

					}
					imageLoader.init(ImageLoaderConfiguration
							.createDefault(getBaseContext()));
					imageLoader.displayImage(imageUrls[0], img_place_view,
							options);
					//
				}
				// Toast.makeText(getApplicationContext(), ""+liked +","+visted,
				// Toast.LENGTH_LONG).show();
			}
		} catch (Exception e) {
			// TODO: handle exception
			Toast.makeText(getApplicationContext(), "null " + e.toString(),
					Toast.LENGTH_LONG).show();
		}

		if (visted) {
			Button btn_visited = (Button) findViewById(R.id.btn_view_tab_place_details_visit);
			btn_visited.setText("Bạn đã đến");
			btn_visit.setBackgroundResource(R.drawable.btn_checkin);
		}
		if (liked) {
			Button btn_liked = (Button) findViewById(R.id.btn_view_tab_place_details_like);
			btn_like.setBackgroundResource(R.drawable.btn_like);
			btn_liked.setText("Bỏ thích");
		}

	}

	public void getImage() {
		try {
			SchemeRegistry registry = new SchemeRegistry();
			registry.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));
			HttpParams httpParams = new BasicHttpParams();
			ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(
					httpParams, registry);
			HttpClient client = new DefaultHttpClient(connMgr, httpParams);
			HttpPost post = new HttpPost(getString(R.string.connectionString)
					+ "vLocationService/loadAllImage");
			post.setHeader("Accept", "application/json");
			post.setHeader("Content-type", "application/json");
			HashMap<String, Object> postParameters = new HashMap<String, Object>();
			postParameters.put("ItemID", PlaceID);
			Gson gson = new Gson();
			String jsonParameters = gson.toJson(postParameters);
			post.setEntity(new StringEntity(jsonParameters));
			HttpResponse response = client.execute(post);
			HttpEntity entity = response.getEntity();
			String jsonresult = EntityUtils.toString(entity);
			Type listType = (Type) new TypeToken<ArrayList<ItemImage>>() {
			}.getType();
			ListImage = gson.fromJson(jsonresult, listType);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}
